package DeviceData 
{
	import Screens.DataEvent;
	import starling.display.Sprite;
	import flash.events.ErrorEvent;
	import starling.events.Event;
	import flash.sensors.Geolocation;
	import flash.events.GeolocationEvent;
	
	/**
	 * @author Simon Claeye
	 */
	public class GeoLocationData extends Sprite
	{
		private var geo:Geolocation;		
		private var recentEvent:GeolocationEvent;
		
		public function GeoLocationData() 
		{
			//Defer intialization until initialize is called.
		}
		
		/**
		 * Function to initialize the gps sensor.
		 */
		public function initialize():void
		{
			if (Geolocation.isSupported)
			{
				geo = new Geolocation();
				geo.addEventListener(GeolocationEvent.UPDATE, geoUpdateHandler);
				if (!geo.muted)
				{
					geo.setRequestedUpdateInterval(5000);	//update every 5 seconds
				}
				else
					dispatchEvent(new GPSErrorEvent(GPSErrorEvent.MUTED));
			}
			else
				dispatchEvent(new GPSErrorEvent(GPSErrorEvent.UNSUPPORTED)); 
		}
		
		public function hasData():Boolean
		{
			return (recentEvent != null);
		}
		
		public function getData():GeolocationEvent
		{
			return recentEvent;
		}
		
		public function stop():void
		{
			geo.removeEventListener(GeolocationEvent.UPDATE, geoUpdateHandler);
		}
		/*
		 * Data returned by geolocation event:
		 * 
		 * Latitude (in degrees):
		 * The geographical coordinate with a value between –90 to +90 degrees.
		 * Negative latitude denotes south and positive latitude denotes north.
		 * 
		 * Longitude (in degrees):
		 * The geographical coordinate with a value between –180 to +180 degrees.
		 * Negative longitude denotes west and positive longitude denotes east.
		 * 
		 * Altidude (in meters):
	     * Vertical height of the geographical coordinates (Latitude and Longitude).
		 * 
		 * Heading (in degrees):
		 * The direction of movement (with respect to true north) in integer degrees
		 * 
		 * see doc for more info: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/events/GeolocationEvent.html#latitude
		 */
		
		private function geoUpdateHandler(event:GeolocationEvent):void
		{
			recentEvent = event;	//remember the most recent event
			dispatchEvent(new DataEvent(DataEvent.LOCATION_CHANGE));
		}
	}
}